package cn.lhl.web.aop;

import cn.lhl.domain.system.SysLog;
import cn.lhl.domain.system.User;
import cn.lhl.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Aspect    //切面类
@Component    //组件
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private HttpSession session;

    @Autowired
    private HttpServletRequest request;

    //代理方法
    @Around(value = "execution( * cn.lhl.web.controller.*.*.*(..))")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {

        //System.out.println("调用日志");

        //创建日志
        SysLog sysLog = new SysLog();

        sysLog.setId(UUID.randomUUID().toString());
        User user = (User) session.getAttribute("loginUser");

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

        if (user!=null&&requestMapping!=null){
            sysLog.setUserName(user.getUserName());
            sysLog.setCompanyId(user.getCompanyId());
            sysLog.setCompanyName(user.getCompanyName());

            sysLog.setTime(new Date());
            sysLog.setIp(request.getLocalAddr());

            sysLog.setMethod(method.getName());   //list.do
            sysLog.setAction(requestMapping.name());   //分页查询企业列表

            //将日志写入数据库
            sysLogService.save(sysLog);
        }

        return pjp.proceed();  //执行被代理方法，list.do
    }
}